<template>
    <div class="hot-posts-container">
        <a-row :gutter="16">
            <a-col :span="6">
                <div class="left-navigation">
                    <a-tabs v-model:activeKey="activeTab" tab-position="left">
                        <a-tab-pane key="hotPosts" tab="热门帖子">
                            <template #tab>
                                热门帖子
                            </template>
                        </a-tab-pane>
                        <a-tab-pane key="flow" tab="热门交流">
                            <template #tab>
                                热门交流
                            </template>
                        </a-tab-pane>
                    </a-tabs>
                </div>
            </a-col>
            <a-col :span="18">
                <div class="content-wrapper">
                    <div class="header">
                        <h1>{{ activeTab === 'hotPosts' ? '热门帖子' : '热门交流' }}</h1>
                    </div>

                    <div class="posts-list">
                        <a-skeleton :loading="loading" active v-if="loading" />
                        <template v-else>
                            <a-list :data-source="postsList">
                                <template #renderItem="{ item, index }">
                                    <a-list-item class="post-item" @click="toPostDetail(item)">
                                        <a-list-item-meta>
                                            <template #title>
                                                <router-link
                                                    :to="{ path: '/social/detail', query: { postId: item.postId } }">
                                                    {{ activeTab === 'hotPosts' ? item.title : truncateContent(sanitizeHtml(item.content), 100) }}
                                                </router-link>
                                            </template>
                                            <template #avatar>
                                                <!-- 显示排名 -->
                                                <strong class="rank-number"> {{ index + 1 }} </strong>
                                            </template>
                                            <template #description>
                                                <a-space>
                                                    <template #split>
                                                        <a-divider type="vertical" />
                                                    </template>
                                                    <div class="post-info">
                                                        <a-avatar :src="item.avatar" :size="24" />
                                                        <span class="author">{{ item.nickname }}</span>
                                                    </div>
                                                    <span v-if="activeTab === 'hotPosts'" class="post-info-item">{{ formatNumber(item.viewCount) }}浏览</span>
                                                    <span v-if="activeTab === 'flow'" class="post-info-item">{{ formatNumber(item.likeCount) }}点赞</span>
                                                    <span class="post-info-item">{{ formatNumber(item.commentCount) }}评论</span>
                                                    <span v-if="activeTab === 'hotPosts'" class="post-info-item">{{ formatNumber(item.collectCount) }}收藏</span>
                                                </a-space>

                                            </template>
                                        </a-list-item-meta>
                                        <div class="post-content">
                                            <a-space>
                                                <FireFilled style="color: #ff4d4f;" />
                                                <strong class="hot-number" v-if="activeTab === 'hotPosts'">{{ formatNumber(item.viewCount) }}</strong>
                                                <strong class="hot-number" v-else>{{ formatNumber(item.likeCount) }}</strong>
                                                <span style="color: rgba(107, 114, 128, 1);">热度</span>
                                            </a-space>
                                        </div>
                                        <template #actions v-if="activeTab === 'hotPosts'">
                                            <a-button 
                                                v-if="item.userId !== userStore.userId"
                                                :loading="collectLoading" 
                                                style="width: 80px;"
                                                :type="item.collectFlag ? 'default' : 'primary'"
                                                @click="handleCollect(item)">
                                                {{ item.collectFlag ? '已收藏' : '收藏' }}
                                            </a-button>
                                        </template>
                                    </a-list-item>
                                </template>
                            </a-list>
                        </template>
                    </div>
                </div>
            </a-col>
        </a-row>
    </div>
    <LoginTooltipMode ref="loginTooltipMode" />
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import LoginTooltipMode from "@/components/LoginTooltipMode/index.vue";
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { FireFilled, PlusOutlined } from '@ant-design/icons-vue';
import DOMPurify from 'dompurify';
import dayjs from 'dayjs';
import { collectPosts, hotList } from '@/api/front/social';
import { HotListVO } from '@/api/front/social/types';
import useUserStore from "@/store/modules/user";
import router from '@/router';

const loading = ref(false);
const loginTooltipMode = ref();
const userStore = useUserStore();

const postsList = ref<HotListVO[]>([]);

const activeTab = ref('hotPosts');
const getHotPosts = async () => {
    loading.value = true;
    try {
        const res = await hotList({ categoryId: activeTab.value === 'hotPosts' ? 0 : 1 });
        postsList.value = res.data;
    } catch (error) {
        message.error('获取数据失败');
    } finally {
        loading.value = false;
    }
};

const truncateContent = (content: string, maxLength: number) => {
    const tempElement = document.createElement('div');
    tempElement.innerHTML = content;
    const text = (tempElement.innerText || tempElement.textContent || '').trim().replace(/\s+/g, ' ');
    return text;
};

const sanitizeHtml = (content: string) => {
    return DOMPurify.sanitize(content);
};

const formatDate = (date: string) => {
    return dayjs(date).format('YYYY-MM-DD HH:mm');
};
const collectLoading = ref(false);
// 收藏帖子
const handleCollect = async (post: any) => {
    collectLoading.value = true;
    try {
        const loginFlag = await loginTooltipMode.value.isLogin();
        if (!loginFlag) {
            return;
        }

        const res = await collectPosts({
            type: post.collectFlag ? 'uncollect' : 'collect',
            authorId: post.userId,
            postsId: post.postId
        });
        
        // 重新获取列表
        getHotPosts();

        message.success('收藏成功');
    } catch (error) {
        message.error('收藏失败');
    } finally {
        collectLoading.value = false;
    }
};

const formatNumber = (num: number): string => {
    if (!num) return '0';
    
    if (num < 1000) {
        return num.toString();
    }
    
    if (num < 10000) {
        // 1000-9999，显示为x.xk
        const k = num / 1000;
        return k.toFixed(1).replace(/\.0$/, '') + 'k';
    }
    
    // 10000及以上，显示为x.xw
    const w = num / 10000;
    return w.toFixed(1).replace(/\.0$/, '') + 'w';
};

const toPostDetail = (post: any) => {
    const routeData = {
        path: '/social/detail',
        query: { postId: post.postId }
    };
    const routeUrl = router.resolve(routeData);
    window.open(routeUrl.href, '_blank');
};

// 监听标签页切换
watch(activeTab, () => {
    getHotPosts();
});

onMounted(() => {
    getHotPosts();
});
</script>

<style lang="scss" scoped>
.hot-posts-container {
    padding: 10px;
    background: #f5f5f5;
    min-height: calc(100vh - 64px);

    .content-wrapper {
        background: #fff;
        padding: 24px;
        border-radius: 8px;

        .header {
            margin-bottom: 24px;
            padding-bottom: 16px;
            border-bottom: 1px solid #f0f0f0;

            h1 {
                margin: 0;
                font-size: 20px;
                font-weight: 500;
                color: #1d2129;
            }
        }

        .posts-list {
            :deep(.ant-list-item-meta-title) {
                margin-bottom: 4px;
                
                a {
                    color: #1d2129;
                    text-decoration: none;
                    display: -webkit-box;
                    -webkit-line-clamp: 2;
                    -webkit-box-orient: vertical;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    line-height: 1.5;

                    &:hover {
                        color: #1890ff;
                    }
                }
            }

            .post-item {
                cursor: pointer;
                padding: 16px;
                margin-bottom: 16px;
                border-radius: 8px;
                &:hover {
                    background: #f0f0f0;
                }
            }

            .post-info {
                display: flex;
                align-items: center;

                .author {
                    font-size: 0.75rem;
                    margin-left: 3px;
                    color: rgba(55, 65, 81, 1);
                    font-weight: bolder;
                }
            }

            .post-info-item {
                font-size: 0.75rem;
            }

            .hot-number {
                font-size: 1.125rem;
                font-weight: bolder;
            }

            .rank-number {
                color: rgba(55, 65, 81, 1);
            }

        }

    }

    .left-navigation {
        width: 240px;
        background: #fff;
        border-radius: 8px;
        box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.03);
        padding: 16px 0;

        :deep(.ant-tabs) {
            height: 100%;

            .ant-tabs-nav {
                width: 100%;
                border-right: none;
                min-height: 100%;

                .ant-tabs-tab {
                    padding: 12px 24px;
                    margin: 0;
                    transition: all 0.3s;

                    &:hover {
                        color: #1677ff;
                        background: #f0f7ff;
                    }

                    &.ant-tabs-tab-active {
                        background: #e6f4ff;

                        .ant-tabs-tab-btn {
                            color: #1677ff;
                            font-weight: 500;
                        }
                    }

                    .anticon {
                        margin-right: 12px;
                    }
                }

                &::before {
                    opacity: 0;
                }
            }

            .ant-tabs-content-holder {
                display: none;
            }
        }
    }
}
</style>
<style scoped>
:deep(.ant-list-split .ant-list-item) {
    border-bottom: none;
}
</style>